const fs = require("fs");

function log(...msg) {
    console.log(msg);
}

function l(msg, file = "test.json") {
    // console.log(JSON.stringify(msg, " ", 2));
    fs.writeFile(file, JSON.stringify(msg, " ", 2), (err) => {
        if (!err) {
            log("ok");
        }
    })
}

class IniHandle {

    // 生成所有内容
    genAll() {
        fs.readdir(`data/Custom`, (err, data) => {
            if (!err) {
                data.forEach(e => this.gen(e));
            } else {
                log("genAll:err", err);
            }
        })
    }
    /**
     * 读取slk并处理
     * @param {*} slkName 
     */
    gen(slkName) {
        fs.readFile(`data/Custom/${slkName}`, 'utf8', (err, fileString) => {
            if (!err) {
                let data = this.parseIni(fileString);
                this.genField(data,slkName);
                this.genTemplate(data,slkName);
            } else {
                log("slkName:err" + slkName, err);
            }
        })
    }

    //将ini解析为json
    parseIni(lniString) {
        let data = [];
        let segment = () => {
            return {
                "name": "",
                "fields": []
            }
        };
        const field = () => {
            return {
                "n": "",
                "d": "",
                "v": "",
            };
        }
        let tempSegment;
        let tempField;
        let isMultiLine = false;
        let MultiLine = "";
        let lines = lniString.split("\r\n");

        lines.forEach((line, i) => {
            if (line[0] == "[") {
                if (tempSegment) {
                    //压入旧数据
                    data.push(tempSegment)
                }
                tempSegment = segment();
                //名称
                tempSegment["name"] = line.replace("[", "").replace(']', "");
                tempSegment["fields"] = [];
            } else if (line[0] == '-') {
                tempField = field();
                //注释
                tempField["d"] = line.replace(/-/g, "").trim();
            } else if (line) {
                if(!tempField){
                    tempField = field();
                }
                //属性
                if(line.includes("{") && !line.includes("}")){
                    //多行属性
                    isMultiLine = true;

                    let temp = line.replace(/"/g, "").replace(/[\s\n\r]/g, "").split("=");
                    tempField["n"] = temp[0];
                    MultiLine = temp[1];
                }else{
                    if(isMultiLine){
                        //多行属性处理
                        if(line.includes("}")){
                            MultiLine += line;
                            tempField["v"] = MultiLine;
                            tempSegment["fields"].push(tempField);
                            tempField = field();
                            isMultiLine = false;
                        }else{
                            MultiLine += line.replace(/[\s\n\r]/g, "");
                        }
                    }else{
                        let temp = line.replace(/"/g, "").replace(/[\s\n\r]/g, "").split("=");
                        tempField["n"] = temp[0];
                        tempField["v"] = temp[1];
                        tempSegment["fields"].push(tempField);
                        tempField = field();
                    }
                }
            }
            if (i == lines.length - 1) {
                data.push(tempSegment)
            }
        })
        return data;
    }

    // 生成field的json
    genField(data,slkName) {
        let fields = {};
        data.forEach(item => {
            item.fields.forEach(field => {
                fields[field["n"]] = {
                    "name":field["n"],     
                    "zh":field["d"],       
                    "default":field["v"], 
                    "detail":"",  
                    "type":this.toType(field["v"]) 
                }
            })
        })
        log("field",slkName,Object.keys(fields).length);
        this.writeJson(
            "field/"+slkName.replace(".ini",".json"),
            fields  
        )
    }

    // 生成模板的json
    genTemplate(data,slkName) {
        let templates = [];
        data.forEach(item => {
            let temp = {
                name:item.name,
                fields:[],
            }
            item.fields.forEach(field => {
                temp.fields.push({
                    [field["n"]]:field["v"]
                })
            });
            templates.push(temp);
        })
        
        log("template",slkName,templates.length);

        this.writeJson(
            "template/"+slkName.replace(".ini",".json"),
            templates,
            true  
        )
    }

    writeJson(file,rawData,raw = false){
        let data =  raw 
            ? JSON.stringify(rawData).replace(/\\\\/g,"\\") 
            : JSON.stringify(rawData," ",2).replace(/\\\\/g,"\\") ;

        fs.writeFile(`out/${file}`,data,err=>{
            if(!err){
                log("ok:"+file);
            }else{
                log("err:"+file,err);
            }
        });
    }
    toType(v){
        let t = parseFloat(v);
        if(typeof t == "number" && !isNaN(t)){
            if((v+"").includes(".")){
                return "float"
            }else{
                return "int"
            }
        }else if(v.includes("{")){
            return "table";
        }else{
            return "string";
        }
    }

    isSpace(s) {
        return s.match(/\s/);
    }


}

const h = new IniHandle();
// 生成字段名称
// h.gen("ability.ini");
h.genAll();
// 生成内置模板